package io.gitee.xjt2016.modules.common.utils.http;

import jodd.util.StringUtil;
import lombok.extern.log4j.Log4j2;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

@Log4j2
public class RetryAndChangeIpInterceptor implements Interceptor {
    String FirstIP;
    String SecondIP;
    int RetryCount;

    public RetryAndChangeIpInterceptor(String firsrIP, String secondIP, int tryCount) {
        FirstIP = firsrIP;
        SecondIP = secondIP;
        RetryCount = tryCount;
    }

    public RetryAndChangeIpInterceptor(String firsrIP, String secondIP) {
        FirstIP = firsrIP;
        SecondIP = secondIP;
        RetryCount = 3;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // try the request
        Response response = chain.proceed(request);
        int tryCount = 0;
        while (!response.isSuccessful() && tryCount <= RetryCount) {
            String url = request.url().toString();
            if (!StringUtil.isBlank(FirstIP) && !StringUtil.isBlank(SecondIP)) {//重定向
                if (url.contains(FirstIP)) {
                    url = url.replace(FirstIP, SecondIP);
                } else if (url.contains(SecondIP)) {
                    url = url.replace(SecondIP, FirstIP);
                }
                Request newRequest = response.request().newBuilder().url(url).build();
                log.debug("intercept {}", "Request is not successful - " + tryCount);
                tryCount++;
                // retry the request
                response = chain.proceed(newRequest);
            } else {
                response = chain.proceed(request);
            }
        }
        return response;
    }
}